import axios from 'axios'

// 基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/sow'

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // 未授权，清除token并跳转到登录页
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 就诊人接口类型定义
export interface Patient {
  id: string
  name: string
  idCard: string
  birthDate: string
  gender: 'male' | 'female'
  bloodType?: 'A' | 'B' | 'AB' | 'O'
  maritalStatus?: 'single' | 'married' | 'divorced' | 'widowed'
  specializedTreatment?: 'yes' | 'no'
  phone: string
  emergencyContact?: string
  emergencyPhone?: string
  address?: string
  notes?: string
  avatar?: string
  createdAt: string
  updatedAt: string
}

export interface CreatePatientRequest {
  name: string
  idCard: string
  birthDate: string
  gender: string
  bloodType?: string
  maritalStatus?: string
  specializedTreatment?: string
  phone: string
  emergencyContact?: string
  emergencyPhone?: string
  address?: string
  notes?: string
  avatar?: string
}

export interface UpdatePatientRequest extends Partial<CreatePatientRequest> {
  id: string
}

export interface PatientListResponse {
  success: boolean
  data: Patient[]
  message?: string
}

export interface PatientResponse {
  success: boolean
  data: Patient
  message?: string
}

// 就诊人API接口
export const patientsApi = {
  // 获取就诊人列表
  getPatients: async (): Promise<PatientListResponse> => {
    try {
      const response = await api.get('/patients')
      return response.data
    } catch (error) {
      console.error('获取就诊人列表失败:', error)
      throw error
    }
  },

  // 获取单个就诊人
  getPatient: async (id: string): Promise<PatientResponse> => {
    try {
      const response = await api.get(`/patients/${id}`)
      return response.data
    } catch (error) {
      console.error('获取就诊人详情失败:', error)
      throw error
    }
  },

  // 添加就诊人
  createPatient: async (data: CreatePatientRequest): Promise<PatientResponse> => {
    try {
      const response = await api.post('/patients', data)
      return response.data
    } catch (error) {
      console.error('添加就诊人失败:', error)
      throw error
    }
  },

  // 添加就诊人（支持文件上传）
  createPatientWithFile: async (formData: FormData): Promise<PatientResponse> => {
    try {
      const response = await api.post('/patients', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      return response.data
    } catch (error) {
      console.error('添加就诊人失败:', error)
      throw error
    }
  },

  // 更新就诊人
  updatePatient: async (data: UpdatePatientRequest): Promise<PatientResponse> => {
    try {
      const response = await api.put(`/patients/${data.id}`, data)
      return response.data
    } catch (error) {
      console.error('更新就诊人失败:', error)
      throw error
    }
  },

  // 删除就诊人
  deletePatient: async (id: string): Promise<{ success: boolean; message?: string }> => {
    try {
      const response = await api.delete(`/patients/${id}`)
      return response.data
    } catch (error) {
      console.error('删除就诊人失败:', error)
      throw error
    }
  },

  // 验证身份证号是否已存在
  checkIdCard: async (idCard: string, excludeId?: string): Promise<{ exists: boolean }> => {
    try {
      const response = await api.get('/patients/check-id-card', {
        params: { idCard, excludeId }
      })
      return response.data
    } catch (error) {
      console.error('验证身份证号失败:', error)
      throw error
    }
  }
}

// 本地存储就诊人数据（用于离线模式）
export const localPatientsStorage = {
  // 获取本地就诊人列表
  getPatients: (): Patient[] => {
    try {
      return JSON.parse(localStorage.getItem('patients') || '[]')
    } catch (error) {
      console.error('获取本地就诊人数据失败:', error)
      return []
    }
  },

  // 保存就诊人到本地
  savePatient: (patient: Patient): void => {
    try {
      const patients = localPatientsStorage.getPatients()
      const existingIndex = patients.findIndex(p => p.id === patient.id)
      
      // 创建不包含头像的数据副本
      const patientWithoutAvatar = {
        ...patient,
        avatar: undefined // 不保存头像数据到本地存储
      }
      
      if (existingIndex >= 0) {
        patients[existingIndex] = patientWithoutAvatar
      } else {
        patients.push(patientWithoutAvatar)
      }
      
      localStorage.setItem('patients', JSON.stringify(patients))
    } catch (error) {
      console.error('保存就诊人到本地失败:', error)
    }
  },

  // 删除本地就诊人
  deletePatient: (id: string): void => {
    try {
      const patients = localPatientsStorage.getPatients()
      const filteredPatients = patients.filter(p => p.id !== id)
      localStorage.setItem('patients', JSON.stringify(filteredPatients))
    } catch (error) {
      console.error('删除本地就诊人失败:', error)
    }
  },

  // 清空本地就诊人数据
  clearPatients: (): void => {
    try {
      localStorage.removeItem('patients')
    } catch (error) {
      console.error('清空本地就诊人数据失败:', error)
    }
  }
}

export default api 